/* 
* FlexContainer Ajax Messaging Wrapper
* Copyright (C) 2009 Michael Paperin
* All rights reserved.
* 
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as 
* published by the Free Software Foundation.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*/
package flexcontainer.ajax
{
	import com.adobe.serialization.json.JSON;
	import flash.events.EventDispatcher;
	import flash.external.ExternalInterface;
	import flexcontainer.ajax.events.ExternalCallObjectEvent;
	
	public class AjaxWrapper extends EventDispatcher
	{
		private static const GAIA_HANDLER:String = "gaiaFlexCallHandler";
		private var _configuration:Object;

		public function get configuration():Object {
			return _configuration;
		}
		
		public function set configuration(value:Object):void {
			_configuration = value;
		}
		
		public function AjaxWrapper(ajaxCallHandler:Function, parameters:Object)
		{
			if (!ExternalInterface.available)
				throw new Error("ExternalInteface is not available at this runtime. JavaScript access will be disabled.");
			try {
				ExternalInterface.addCallback("FlexCallObject", containerCallObject);
				addEventListener(ExternalCallObjectEvent.ONCALL, ajaxCallHandler);
				
 				var s:String = parameters.config;
 				if(s != null && s.length > 0)
					configuration = JSON.decode(s);
				if(configuration.initialData != null) {
					try {
						configuration.initialData = JSON.decode(configuration.initialData);
					}
					catch(e:Error) {}
				}
			}
			catch (e:Error) {
				throw e;
			}
		}
		
		private function containerCallObject(jsonObject:String):void
		{
			var data:Object = JSON.decode(jsonObject) as Object;
			dispatchEvent(new ExternalCallObjectEvent(ExternalCallObjectEvent.ONCALL, data));
		}
		
		public function callToAjax(data:Object):void
		{
			ExternalInterface.call(GAIA_HANDLER, configuration.containerId, JSON.encode(data));
		}
	}
}
